import json
import sys
from .alarm_data import add
from flask import request,jsonify
import logging
import os
import subprocess
from .normal_data import add as normal_datas
from configparser import ConfigParser
import pymysql.cursors
import base64
import requests
# 读取配置文件
conf = ConfigParser()
conf.read("setting.ini",encoding='utf-8')
# 数据库连接
def mysql():
    mydb = pymysql.connect(
        host=conf.get("mysql_settings","host"),
        port=int(conf.get("mysql_settings","port")),
        user=conf.get("mysql_settings","user"),
        password=conf.get("mysql_settings","password"),
        database='data_info',
        cursorclass=pymysql.cursors.DictCursor
    )
    return mydb


def data_analysis():

    try:
        jsons = json.loads(request.data)
        mydb = mysql()
        mydb.connect()
        cursor = mydb.cursor()
        data = '"'+str(jsons)+'"'
        sql = "insert into all_data (data,type) values(%s,'%s')"%(data,'hx100')
        insert = cursor.execute(sql)
        mydb.commit()
        cursor.close()  # 关闭游标
        mydb.close() # 关闭连接
        path = './analysis'
        files = os.listdir(path)

        for f in files:
            path = './analysis/'+f
            cmd = "python3 "+path+" --data='"+str(jsons).replace("'",'"')+"'"
            sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            out, err = sp.communicate()
            issued = out.decode(encoding='utf-8',errors='strict')
            if 'None' in issued or issued =='':
                print("解析失败")
            else:
                print(issued.replace("'",'"'))
                issued = json.loads(issued.replace("'",'"'))
                print(issued)
                if 'alarm' in issued:
                    alarm = issued['alarm']
                    # 报警数据
                    json_alarm_data = {}
                    json_alarm_data['number'] = issued['number']
                    json_alarm_data['alarmType'] = alarm['alarmType']
                    json_alarm_data['alarmTypeName'] = alarm['alarmTypeName']
                    json_alarm_data['content'] = alarm['content']
                    json_alarm_data['alarmTime'] = issued['time']
                    json_alarm_data['dataType'] = 'alarm'
                    if 'url' in alarm:
                        json_alarm_data['url'] = alarm['url']
                    add(json_alarm_data)
                if 'normal' in issued:
                    normal = issued['normal']
                    # 正常数据
                    json_normal_data = {}
                    json_normal_data['number'] = issued['number']
                    json_normal_data['paramInfo'] = normal['paramInfo']
                    json_normal_data['time'] = issued['time']
                    json_normal_data['type'] = 'nonono'
                    json_normal_data['dataType'] = 'normal'
                    normal_datas(json_normal_data)
                break
    except Exception as e:
        logging.debug('data_analysis:%s'%e)
    return jsonify(
        msg="success",
        code=0
    )


# 误报图片保存上传
def false_alarm_image():
    try:
        jsons = request.json
        url = jsons['url']
        ip,path = url.split('upload')
        path = '/mnt/work/www/upload'+path
        f = open(path, "rb")
        # 读取文件的内容转换为base64编码
        ls_f = str(base64.b64encode(f.read()),'utf-8')
        jsons['base64Images'] = ls_f
        f.close()
        headers = {
            "Content-Type": "application/json; charset=UTF-8",
            "Referer": "http://jinbao.pinduoduo.com/index?page=5",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
        }
        url = "http://gw.wisdiot.com:8606/dataRelay/dataRelay/falseAlarmImage"
        response = requests.post(url, data=json.dumps(jsons), headers=headers,timeout=5).text
        response = json.loads(response)
        print(response)
    except Exception as e:
        print(e)
    return jsonify(
        msg="success",
        code=0
    )
